<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './template.data';
  import { createTemplate, updateTemplate } from '@/api/template/template';
  import type { TemplateAddReq, TemplateEditReq } from '@/api/template/model/templateModel';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const rowId = ref<number>(0);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增模板' : '编辑模板'));

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      const formData = {
        name: values.name,
        desc: values.desc,
        cover: Array.isArray(values.cover) ? values.cover[0]?.url || values.cover[0] : values.cover,
        status: values.status,
      };

      if (unref(isUpdate)) {
        await updateTemplate({
          ...formData,
          id: rowId.value,
        } as TemplateEditReq);
      } else {
        await createTemplate(formData as TemplateAddReq);
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
